package com.anysoft.login;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.AccountLoginBean;
import com.anysoft.bean.QueryCertificateTypeBean;
import com.anysoft.bean.ResultBean;
import com.anysoft.bean.UserBean;
import com.anysoft.event.FundBannerLoginEvent;
import com.anysoft.event.HomeBannerLoginEvent;
import com.anysoft.event.RegisterSuccessEvent;
import com.anysoft.user.RetrievePwdActivity;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.AnalyticsEventUtils;
import com.anysoft.utils.AnalyticsUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.RSACryptographyUtil;
import com.anysoft.utils.login.PicDowload;
import com.anysoft.utils.login.PictureCodeNetUtil;
import com.anysoft.view.CustomMarqueeTextView;
import com.anysoft.view.picker.NomarlPickerPopupWindow;
import com.anysoft.web.SearchTradeNewActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.anysoft.MentorConst.ACCOUNT_LOCKOUT;

/**
 * Created by wwq on 2017/1/17.
 */

public class LoginActivity extends BaseActivity {

    private static final int ERROR_SHOW_TIME = 5;
    private static final int LOAD_CODE = 99;
    private static final int ENABLE_IMG = 98;
    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.rightButton)
    TextView rightButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.cmtv_title)
    CustomMarqueeTextView cmtvTitle;
    @BindView(R.id.titlebar)
    FrameLayout titlebar;
    @BindView(R.id.tv_login_error_msg)
    TextView tvLoginErrorMsg;
    @BindView(R.id.iv_user_img)
    ImageView ivUserImg;
    @BindView(R.id.tv_login_forget_pwd)
    TextView tvLoginForgetPwd;
    @BindView(R.id.tv_login_user_type)
    TextView tvLoginUserType;
    @BindView(R.id.et_login_user_id)
    EditText etLoginUserId;
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_text)
    TextView tvText;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.et_login_pwd)
    EditText etLoginPwd;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.iv_login_verification_code)
    ImageView ivLoginVerificationCode;
    @BindView(R.id.et_login_verification_code)
    EditText etLoginVerificationCode;
    @BindView(R.id.rl_login_verification_code)
    RelativeLayout rlLoginVerificationCode;
    @BindView(R.id.rl_login_container)
    RelativeLayout rl_login_container;
    @BindView(R.id.tv_login_tip)
    TextView tvLoginTip;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.rootview)
    LinearLayout rootview;
    @BindView(R.id.cb_login_remember_id_no)
    CheckBox cb_login_remember_id_no;

    private NomarlPickerPopupWindow nomarlPickerPopupWindow;
    private int currentPosition;
    private int selectPosition = -1;
    List<QueryCertificateTypeBean.DataBean> idTypeList = new ArrayList<>();
    ArrayList<String> list = new ArrayList<>();

    private Animation showAnim = null;
    private Animation hideAnim = null;

    private Timer timer;
    private int time = 0;

    private boolean idTypePopShow = false;
    private boolean isShowPwd = false;

    private boolean isFirstComing = true;
    private String typeValue = "0";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        rightButton.setVisibility(View.INVISIBLE);
//        rightButton.setText("开户");
        title.setText("登录");
        tvLoginUserType.setText("身份证");
        showAnim = AnimationUtils.loadAnimation(this, R.anim.top_in);
        hideAnim = AnimationUtils.loadAnimation(this, R.anim.top_out);

        getIdType();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void getIdType() {
        Map<String, String> params = new HashMap<>();
        params.put("type", "1");
        Logger.t("-----BASE_URL-----").d(HttpUtils.createRequestUrl(this, HostConstant.QUERY_CERTIFICATE_TYPE, params));
        OkGo.<String>post(HostConstant.QUERY_CERTIFICATE_TYPE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateIdType(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void UpdateIdType(String json) {
        idTypeList.clear();
        list.clear();

        QueryCertificateTypeBean bean;
        try {
            bean = new Gson().fromJson(json, QueryCertificateTypeBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
//            rlLoginVerificationCode.setVisibility(View.VISIBLE);
            return;
        }

        if (bean == null || bean.getData() == null ||
                bean.getData().isEmpty() || bean.getData().size() < 1) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        idTypeList.addAll(bean.getData());
        for (QueryCertificateTypeBean.DataBean dataBean : idTypeList) {
            list.add(dataBean.getTypeName());
        }

        if (isFirstComing) {
            isFirstComing = false;
            selectPosition = 0;
            tvLoginUserType.setText(idTypeList.get(selectPosition).getTypeName().length() > 4 ?
                    idTypeList.get(selectPosition).getTypeName().substring(0, 4) :
                    idTypeList.get(selectPosition).getTypeName());
        }

        if (idTypePopShow) {
            showTypePicker();
        }
    }

    private void showTypePicker() {
        if (nomarlPickerPopupWindow == null) {
            nomarlPickerPopupWindow = new NomarlPickerPopupWindow(mActivity, itemsOnClick, list);
        }
        nomarlPickerPopupWindow.showAtLocation(findViewById(R.id.rootview),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        nomarlPickerPopupWindow.setOnPickerChangeListener(
                new NomarlPickerPopupWindow.OnPickerChangeListener() {
                    @Override
                    public void onPickerChange(int position) {
                        currentPosition = position;
                    }
                });
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_cancel:
                    if (nomarlPickerPopupWindow != null) {
                        nomarlPickerPopupWindow.dismiss();
                        nomarlPickerPopupWindow = null;
                    }
                    break;
                case R.id.btn_sure:
                    if (nomarlPickerPopupWindow != null) {
                        selectPosition = currentPosition;
                        nomarlPickerPopupWindow.dismiss();

                        tvLoginUserType.setText(idTypeList.get(selectPosition).getTypeName().length() > 4 ?
                                idTypeList.get(selectPosition).getTypeName().substring(0, 4) :
                                idTypeList.get(selectPosition).getTypeName());

                        nomarlPickerPopupWindow = null;
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @OnClick({R.id.leftButton, R.id.rightButton, R.id.tv_login_forget_pwd, R.id.tv_login_user_type,
            R.id.iv_right, R.id.tv_login_tip, R.id.btn_login, R.id.iv_login_verification_code, R.id.btn_register})
    public void onClick(View view) {
        collapseSoftInputMethod(view.getWindowToken());
        switch (view.getId()) {
            case R.id.leftButton:
                HostConstant.SKIP_TYPE = "";
                finish();
                break;
            case R.id.rightButton:
            case R.id.btn_register:
                ActivityUtils.gotoRegisterStep1_1Activity(this);
//                finish();
                break;
            case R.id.tv_login_forget_pwd:
                startActivity(new Intent().setClass(mActivity, RetrievePwdActivity.class));
                finish();
                break;
            case R.id.iv_login_verification_code:
                getVerifyCode("");
                break;
            case R.id.tv_login_user_type:
                idTypePopShow = true;
                currentPosition = 0;

                if (list != null && !list.isEmpty() && list.size() > 0) {
                    showTypePicker();
                } else {
                    getIdType();
                }
                break;
            case R.id.iv_right:
                String str = etLoginPwd.getText().toString();
                if (isShowPwd) {
                    etLoginPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    isShowPwd = false;
                    ivRight.setBackgroundResource(R.mipmap.icon_eye_close);
                } else {
                    etLoginPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    isShowPwd = true;
                    ivRight.setBackgroundResource(R.mipmap.icon_eye);
                }
                etLoginPwd.setSelection(str.length());
                break;
            case R.id.tv_login_tip:
                selectWarmPromptByType("1");
                break;
            case R.id.btn_login:
                if (TextUtils.isEmpty(etLoginUserId.getText().toString())) {
                    showConfirmAlert(mActivity, "提示", "证件号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(etLoginPwd.getText().toString())) {
                    showConfirmAlert(mActivity, "提示", "密码不能为空");
                    return;
                }
                if (rlLoginVerificationCode.isShown() && TextUtils.isEmpty(etLoginVerificationCode.getText().toString().trim())) {
                    showConfirmAlert(mActivity, "提示", "验证码不能为空");
                    return;
                }
                login();
                break;
        }
    }

    private void login() {
        showLoading(mActivity);
        String password = etLoginPwd.getText().toString();
        String rsaKey = getRsaKey();
        String rsaEncodePassword = "";
        if (!TextUtils.isEmpty(rsaKey)) {
            rsaEncodePassword = RSACryptographyUtil.encryptByPublicKey(password, rsaKey);
        }
        if (selectPosition < 0) {
        } else {
            typeValue = idTypeList.get(selectPosition).getTypeValue();
        }
        String loginUserId = etLoginUserId.getText().toString();
        if (rlLoginVerificationCode.isShown()) {
            Map<String, String> params = new HashMap<>();
            params.put("identityType", typeValue);
            params.put("identityNo", loginUserId);
            params.put("tradePassword", rsaEncodePassword);
            params.put("identifyingCode", etLoginVerificationCode.getText().toString());

            final String loginStr = HttpUtils.createRequestUrl(this, HostConstant.LOGIN, params);
            Logger.t("-----Login_Url-----").d(loginStr);

            new Thread() {
                @Override
                public void run() {
                    // 把网络访问的代码放在这里
                    String json = PictureCodeNetUtil.getJsonByUrl(HostConstant.LOGIN, loginStr.split("[?]")[1].replace("+", "%2B"));
                    MentorLogger.LogJson("VerificationCodeLogin---", json);
                    UpdateJson(json, true);
                }
            }.start();
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("identityType", typeValue);
            params.put("identityNo", loginUserId);
            params.put("tradePassword", rsaEncodePassword);

            Logger.t("-----BASE_URL-----").d(HttpUtils.createRequestUrl(this, HostConstant.LOGIN, params));
            OkGo.<String>post(HostConstant.LOGIN)
                    .tag(this)
                    .params(HttpUtils.getCommonParams(this, params))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            UpdateJson(response.body(), false);
                        }


                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            hideLoading();
                            HostConstant.SKIP_TYPE = "";
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }
                    });
        }
    }

    private void UpdateJson(String json, boolean isVerificationCodeShow) {
        if (!isVerificationCodeShow) {
            hideLoading();
        }
        AccountLoginBean bean;
        try {
            bean = new Gson().fromJson(json, AccountLoginBean.class);
        } catch (Exception exception) {
            showErrorTip("数据解析异常，请联系管理员");
            return;
        }

        ResultBean resultBean = checkStateBean(bean, json);
        if (!resultBean.isSuccess()) {
            if (ACCOUNT_LOCKOUT.equals(resultBean.getCode())) {
//                showConfirmAlert(mActivity, "提示", resultBean.getTip(), "确定");
//                return;
            }
            if (!isVerificationCodeShow) {
                if (resultBean.getTip().contains("密码错误")) {
                    showErrorTip("");
//                    showErrorTip(resultBean.getTip());
                }
            }
            getVerifyCode(resultBean.getTip());
            HostConstant.SKIP_TYPE = "";
            return;
        }

        loginSuccess(bean);
    }

    private void loginSuccess(AccountLoginBean bean) {
        AnalyticsEventUtils.toLoginNormalEvent(this);
        AnalyticsUtils.onAnalyticsLogin(bean.getData().getIdentityNo());

        PreferencesUtils.putBoolean(this, findUserId() + "CanGesture", true);
        if (!etLoginUserId.getText().toString().equals(findUserId())) {
            clearSecretKey(mActivity);
        }
        UserBean userBean = new UserBean();
        userBean.setUserName(bean.getData().getRealName());
        userBean.setUserId(bean.getData().getIdentityNo());
        userBean.setUserType(bean.getData().getIdentityType());
        userBean.setToken(bean.getData().getToken());
        userBean.setFundCustomerNo(bean.getData().getFundCustomerNo());
        userBean.setSex(bean.getData().getSex());
        userBean.setRecordIdentNumber(cb_login_remember_id_no.isChecked() ? "1" : "0");
        userBean.setLastLoginTime(System.currentTimeMillis());
        saveUser(userBean, bean);
        PreferencesUtils.putString(this, MentorConst.LAST_LOGIN_USER_ID, bean.getData().getIdentityNo());
        if ("from_redeem".equals(HostConstant.SKIP_TYPE)) {
            ActivityUtils.gotoAssetsFundActivity(this);
        } else if ("from_salary".equals(HostConstant.SKIP_TYPE)) {
            ActivityUtils.gotoFixInvestmentAllActivity(this);
        } else if ("from_query".equals(HostConstant.SKIP_TYPE)) {
            startActivity(new Intent().setClass(this, SearchTradeNewActivity.class));
        } else if ("from_home_banner".equals(HostConstant.SKIP_TYPE)) {
            EventBus.getDefault().post(new HomeBannerLoginEvent(true));
        } else if ("from_fund_banner".equals(HostConstant.SKIP_TYPE)) {
            EventBus.getDefault().post(new FundBannerLoginEvent(true));
        }
        HostConstant.SKIP_TYPE = "";
        finish();
    }

    /**
     * 获取验证码
     */
    private void getVerifyCode(String message) {
        Message msg = new Message();
        msg.what = LOAD_CODE;
        Bundle bundle = new Bundle();
        bundle.putString("message", message);
        msg.setData(bundle);
        mHandler.sendMessage(msg);
        MentorLogger.Log(TAG, "获取验证码地址：" + HostConstant.PICTURE_CHECK_CODE);
        showVerificationCode();
    }

    /**
     * 显示验证码
     */
    private void showVerificationCode() {
        String requestUrl = HostConstant.PICTURE_CHECK_CODE;
        MentorLogger.Log(TAG, "验证码请求URL：" + requestUrl);
        new PicDowload() {

            @Override
            protected void ImageDowloadedBefore() {
            }

            @SuppressWarnings("deprecation")
            @Override
            protected void ImageDowloaded(Bitmap result) {
                if (result == null) {
                    showToast("验证码获取失败，请重试");
                } else {
                    ivLoginVerificationCode.setBackgroundDrawable(new BitmapDrawable(result));
                    enableImagView();
                }

            }
        }.execute(HostConstant.PICTURE_CHECK_CODE);
    }

    /**
     * 允许点击ImageView
     */
    private void enableImagView() {
        ivLoginVerificationCode.setEnabled(true);
        Message msg = new Message();
        msg.what = ENABLE_IMG;
        msg.obj = ivLoginVerificationCode;
        mHandler.sendMessage(msg);
    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("deprecation")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOAD_CODE: // 加载验证码
                    hideLoading();
                    String message = msg.getData().getString("message");
                    if (!TextUtils.isEmpty(message)) {
                        showConfirmAlert(mActivity, "提示", message);
                    }
                    rlLoginVerificationCode.setVisibility(View.VISIBLE);
                    ivLoginVerificationCode.setEnabled(false);
                    ivLoginVerificationCode.setVisibility(View.GONE);
                    break;
                case ENABLE_IMG:
                    hideLoading();
                    ((View) msg.obj).setVisibility(View.VISIBLE);
//                    rlLoginVerificationCode.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    private void showErrorTip(String msg) {
        rlLoginVerificationCode.setVisibility(View.VISIBLE);

        if (!TextUtils.isEmpty(msg)) {
            tvLoginErrorMsg.setText(msg);
        }
        if (!tvLoginErrorMsg.isShown()) {
            tvLoginErrorMsg.startAnimation(showAnim);
            tvLoginErrorMsg.setVisibility(View.VISIBLE);
        }

        if (timer != null) {
            timer.cancel();
        }
        runTimerTask();
    }

    private void hideErrorTip() {
        tvLoginErrorMsg.startAnimation(hideAnim);
        tvLoginErrorMsg.setVisibility(View.INVISIBLE);
    }

    /**
     * 验证码重发倒计时
     */
    private void runTimerTask() {
        timer = new Timer();
        time = ERROR_SHOW_TIME;
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = ERROR_SHOW_TIME;
                msg.obj = time;
                handler.sendMessage(msg);
                time--;
            }
        };
        timer.schedule(task, 0, 1000);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ERROR_SHOW_TIME:
                    if ((Integer) msg.obj <= 0) {
                        if (timer != null) {
                            timer.cancel();
                        }
                        hideErrorTip();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (timer != null) {
            timer.cancel();
        }
        hideLoading();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGestureSetCallBack(RegisterSuccessEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            HostConstant.SKIP_TYPE = "";
            finish();
        }
        return true;
    }
}
